package com.qj.platform.pay.core.dao;

import com.qj.base.commons.utils.CodeGenerator;
import com.qj.platform.pay.core.domain.Operator;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Repository
public class OperatorDao {

    @Autowired
    @Qualifier("jdbcTemplate")
    private JdbcTemplate jdbcTemplate;

    public Operator getUserByUserName(String username) {
        Operator user = null;
        String sql = "SELECT id, name, password, remark, nick_name FROM sys_operator where name=?";
        List<Operator> list = jdbcTemplate.query(sql, new Object[]{username}, initRowMapper());
        if (list != null && list.size() > 0) {
            user = list.get(0);
        }
        return user;
    }

    public RowMapper<Operator> initRowMapper() {
        RowMapper<Operator> rowMapper = new RowMapper<Operator>() {
            public Operator mapRow(ResultSet rs, int rowNum) throws SQLException {
                Operator object = new Operator();
                object.setId(rs.getString("id"));
                object.setName(rs.getString("name"));
                object.setPassword(rs.getString("password"));
                object.setNickName(rs.getString("nick_name"));
                return object;
            }
        };
        return rowMapper;
    }

    public void addUser(String userName,String password,String nickName){
        StringBuilder sql=new StringBuilder("insert into sys_operator(id,name,password,nick_name) values(?,?,?,?)");
        jdbcTemplate.update(sql.toString(), CodeGenerator.getUUID32(),userName,password, nickName);
    }

    public void updateUser(String id,String password,String nickName){
        StringBuilder sql=new StringBuilder("update sys_operator set password=? ");
        List<Object> argList=new ArrayList<>();
        argList.add(password);
        if(StringUtils.isNotEmpty(nickName)){
            sql.append(",nick_name=?");
            argList.add(nickName);
        }
        sql.append(" where id=?");
        argList.add(id);
        jdbcTemplate.update(sql.toString(),argList.toArray(new Object[]{}));
    }
 }
